﻿<FluentTreeView Items="@Items" LazyLoadItems="true" Class="no-selected-indicator">
    <ItemTemplate>
        <FluentCheckbox Value="@(SelectedItems.Contains(context))"
                        ValueChanged="@(e => CheckboxHandler(e, context))"
                        Style="margin-right: 12px;">
            @context.Text
        </FluentCheckbox>
    </ItemTemplate>
</FluentTreeView>

<div>
    <b>Selected items:</b> @(string.Join("; ", SelectedItems.Select(i => i.Text)))
</div>

<style>
    .no-selected-indicator fluent-tree-item[selected]::part(positioning-region) {
        background-color: var(--neutral-fill-stealth-rest);
    }

    .no-selected-indicator fluent-tree-item::part(positioning-region):hover {
        background-color: var(--neutral-fill-stealth-rest);
    }

    .no-selected-indicator fluent-tree-item[selected]::after {
        display: none;
    }
</style>

@code
{
    private int Count = -1;
    private IEnumerable<ITreeViewItem> Items = new List<ITreeViewItem>();
    private List<ITreeViewItem> SelectedItems = new List<ITreeViewItem>();

    protected override void OnInitialized()
    {
        Items = CreateTree(maxLevel: 3, nbItemsPerLevel: 5).Items ?? [];
    }

    // Add or remove item from the selected items list
    private void CheckboxHandler(bool selected, ITreeViewItem item)
    {
        if (selected && !SelectedItems.Contains(item))
        {
            SelectedItems.Add(item);
        }
        else if (!selected && SelectedItems.Contains(item))
        {
            SelectedItems.Remove(item);
        }
    }

    // Recursive method to create tree
    private TreeViewItem CreateTree(int maxLevel, int nbItemsPerLevel, int level = 0)
    {
        Count++;

        var treeItem = new TreeViewItem
            {
                Text = $"Item {Count}",
                Items = level == maxLevel
                              ? null
                              : new List<TreeViewItem>(Enumerable.Range(1, nbItemsPerLevel)
                                                                 .Select(i => CreateTree(maxLevel, nbItemsPerLevel, level + 1))),
            };

        return treeItem;
    }
}
